<?php
#
# dmBridge: a data access framework for CONTENTdm(R)
#
# Copyright © 2009, 2010, 2011 Board of Regents of the Nevada System of Higher
# Education, on behalf of the University of Nevada, Las Vegas
#

/**
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
class DMCPCommentController extends DMCPAdminController {

	public function configure() {
		$this->preFlightCheck();

		$this->setForm(new DMCPCommentSettingsForm());

		if (DMHTTPRequest::getCurrent()->getMethod() == DMHTTPMethod::POST) {
			$this->handleForm();
		}

		$cq = new DMCommentQuery(DMDataStoreFactory::getDataStore());
		$cq->setApproved(-1);
		$cq->getSearchResults();
		$this->tpl_vars['are_unapproved_comments'] = $cq->getNumResults();
		$this->tpl_vars['enable'] = $this->getForm()
				->getFieldByName('enable')->getHTMLTag();
		$this->tpl_vars['moderation'] = $this->getForm()
				->getFieldByName('moderation')->getHTMLTag();
		$this->tpl_vars['notification'] = $this->getForm()
				->getFieldByName('notification')->getHTMLTag();
		$this->tpl_vars['notification_email'] = $this->getForm()
				->getFieldByName('notification_email')->getHTMLTag();

		$this->renderTemplate("/templates/comment/configure.html.php");
		die;
	}

	public function search() {
		$this->preFlightCheck();
		$req = DMHTTPRequest::getCurrent();
		$ds = DMDataStoreFactory::getDataStore();

		$term = $req->getURI()->getQueryValue("q");
		$alias = $req->getURI()->getQueryValue("alias");
		$alias = DMCollection::getSanitizedAlias($alias);
		$results = array();
		$num_results = 0;
		if ($term && $alias) {
			$pred = new DMQueryPredicate();
			$pred->setString($term);
			$cq = new DMCommentQuery($ds);
			$cq->setApproved(0);
			try {
				if ($alias != "/dmdefault") {
					$col = DMCollectionFactory::getCollection($alias);
					$cq->addCollection($col);
					$this->tpl_vars['collection'] = $col;
				}
				$cq->setNumResultsPerPage(1000);
				$cq->addPredicate($pred);
				$results = $cq->getSearchResults();
				$num_results = $cq->getNumResults();
			} catch (DMUnavailableModelException $e) {
				// invalid collection supplied; abort the search
			}
		}

		if ($req->getMethod() == DMHTTPMethod::POST) {
			switch (substr($req->getRepresentation()->getFormValue("action"), 0, 6)) {
			case "Update":
				$flash = new DMFlash(
						DMLocalizedString::getString("NO_COMMENT_SELECTED"), false);
				$rep = $req->getRepresentation();
				if (is_array($rep->getFormValue("id"))) {
					$comments = array();
					foreach ($rep->getFormValue("id") as $id) {
						if ($id <> round($id) || $id < 0 || $id > 1000000) {
							continue;
						}
						$comments[] = $ds->loadComment((int) $id);
					}
					$this->approveAndUpdateComments($comments);
					$flash = new DMFlash(
						DMLocalizedString::getString("COMMENT_UPDATED"), true);
				}
				$req->getSession()->setFlash($flash);
				DMHTTPRequest::reload();
				die;
			case "Delete":
				$flash = new DMFlash(
						DMLocalizedString::getString("NO_COMMENT_SELECTED"), false);
				$rep = $req->getRepresentation();
				if (is_array($rep->getFormValue("id"))) {
					foreach ($rep->getFormValue("id") as $id) {
						if ($id <> round($id) || $id < 0 || $id > 1000000) {
							continue;
						}
						$comment = $ds->loadComment((int) $id);
						DMDataStoreFactory::getDataStore()->deleteComment($comment);
					}
					$flash = new DMFlash(
						DMLocalizedString::getString("COMMENT_DELETED"), true);
				}
				$req->getSession()->setFlash($flash);
				DMHTTPRequest::reload();
				die;
			}
		}

		$this->tpl_vars['term'] = DMString::websafe(substr($term, 0, 50));
		$this->tpl_vars['results'] = $results;
		$this->tpl_vars['num_results'] = $num_results;

		$this->renderTemplate("/templates/comment/search.html.php");
		die;
	}

	public function moderate() {
		$this->preFlightCheck();

		if (DMHTTPRequest::getCurrent()->getMethod() == DMHTTPMethod::POST) {
			$rep = DMHTTPRequest::getCurrent()->getRepresentation();
			if (is_array($rep->getFormValue("id"))) {
				$comments = array();
				$ds = DMDataStoreFactory::getDataStore();
				foreach ($rep->getFormValue("id") as $id) {
					$comments[] = $ds->loadComment((int) $id);
				}
				try {
					switch (strtolower(
							substr($rep->getFormValue("moderate"), 0, 6))) {
					case 'approv':
						$this->approveAndUpdateComments($comments);
						break;
					case 'reject':
						foreach ($comments as $c) {
							$ds->deleteComment($c);
						}
						break;
					}
				} catch (DMDataStoreException $e) {
					DMHTTPRequest::getCurrent()->getSession()->setFlash(
							new DMFlash($e->getMessage(), false));
				}
			} else {
				DMHTTPRequest::getCurrent()->getSession()->setFlash(new DMFlash(
					DMLocalizedString::getString("NO_COMMENT_SELECTED"), false));
			}
		}

		try {
			$cq = new DMCommentQuery(DMDataStoreFactory::getDataStore());
			$cq->setApproved(-1);
			$cq->setSortFields(array("posted_at" => "desc"));
			$this->tpl_vars['comments'] = $cq->getSearchResults();
		} catch (DMException $e) {
			$this->tpl_vars['comments'] = array();
		}

		$this->renderTemplate("/templates/comment/moderate.html.php");
		die;
	}

	public function statistics() {
		$this->preFlightCheck();

		$this->tpl_vars['collections'] = DMCollection::getAuthorized();
		$ds = DMDataStoreFactory::getDataStore();
		$cq = new DMCommentQuery($ds);
		$cq->setApproved(1);
		$cq->getSearchResults();
		$this->tpl_vars['most_commented_objects']
				= DMDataStoreFactory::getDataStore()
				->getObjectsWithMostComments(50);
		$this->tpl_vars['num_comments'] = $cq->getNumResults();
		$this->tpl_vars['num_objects_with_approved_comments']
				= DMDataStoreFactory::getDataStore()
				->getNumObjectsWithApprovedComments();

		$this->renderTemplate("/templates/comment/statistics.html.php");
		die;
	}

	private function approveAndUpdateComments(array $comments) {
		foreach ($comments as $c) {
			if (!$c instanceof DMComment) {
				continue;
			}
			$rep = DMHTTPRequest::getCurrent()->getRepresentation();
			$updated_authors = $rep->getFormValue("author");
			$updated_emails = $rep->getFormValue("email");
			$updated_values = $rep->getFormValue("body");
			$c->setApproved(true);
			$c->setName($updated_authors[$c->getID()]);
			$c->setEmail($updated_emails[$c->getID()]);
			$c->setValue($updated_values[$c->getID()]);
			DMDataStoreFactory::getDataStore()->saveComment($c);
		}
		DMHTTPRequest::getCurrent()->getSession()->setFlash(new DMFlash(
				DMLocalizedString::getString("COMMENT_APPROVED"), true));
	}

}
